<template>
  <div>

    <div class="user-container">

      <div v-if="userInfo.nickName">
        <img class="avatar" :src="userInfo.avatarUrl" alt="">
        <div>
          {{userInfo.nickName}}
        </div>
        <button @click="scanBook" type="warn">立即添加你喜欢的图书吧！</button>
      </div>
      <div v-else>
        <img class="avatar" src="http://image.shengxinjing.cn/rate/unlogin.png" alt="">
        <button @getuserinfo="onGetUserInfo" open-type="getUserInfo">登录</button>
      </div>
    </div>
  </div>
</template>

<script>
  // 先获取数据库的引用
  const db = wx.cloud.database();
  export default {
    data() {
      return {
        userInfo: wx.getStorageSync('userInfo') || {}
      }
    },
    created() {

    },
    methods: {
      async addBook(isbn) {
        console.log(isbn)
        const {result} = await wx.cloud.callFunction({
          name: 'douban',
          data: {isbn}
        });
        result.ocunt = 0;
        result.userInfo = this.userInfo;
        const add = await db.collection('yggBook').add({
          data: result
        });

        if (add._id) {
          wx.showModal({
            title: '添加成功',
            content: `${result.title} 添加成功`
          })
        }
        console.log('bookInfo', bookInfo)


      },
      scanBook() {
        wx.scanCode({
          success: res => {
            const isbn = res.result;
            this.addBook(isbn)
          }
        })
      },
      //获取用户信息，并实现本地缓存已登陆的用户信息
      onGetUserInfo(e) {
        let userInfo = e.mp.detail.userInfo;
        //   调用云函数
        wx.cloud.callFunction({
          name: 'login',
          complete: (res) => {
            userInfo.openid = res.result.openid;
            this.userInfo = userInfo;
            //  本地存储一下
            wx.setStorageSync('userInfo', userInfo)
          }
        });
      }
    }
  }
</script>

<style>
  .user-container {
    text-align: center;
    padding: 20px;
  }

  .avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
  }

</style>
